<?
	$db = new PDO("sqlite:delicious.db");

# maybe colocar num file a parte
function randomDate() {
	$randYear = rand(1970, 1995);
	$randMonth = rand(1, 12);
	$randDay = rand(1, 31);

	return $randYear . '/' . $randMonth . '/' . $randDay;
}

function randomArray($max) {
	$num = rand (1, $max);
	$linkArray = array(); # Each key points to a link
	for ($it = 0; $it < $num; $it++) {
		
		$key = rand(1, $max);
		$linkArray[$key] = $key; # This way we make there aren't 
								 # duplicate links
	}
	return $linkArray;
}

include('configuration.php');
include('querys.php');

# reset db

# import files
$userList = file('db/users.txt');
$passList = file('db/pass.txt');

# Populate users and passwords
$id = 1;
foreach ($userList as $line_num => $user) {
	$user = trim($user);
	
	$password = $passList[$line_num]; 
	$password = trim($password);
	
	$email = "$user@gmail.com"; 
	$email = trim($email);
	
	$birth = randomDate(); 
	$birth = trim($birth);
	
	if ($DEBUG == 1) { echo '</p>' . $user . ' '. $password . ' ' . $email . ' ' . $birth . '</p>';}

	$userInsert->execute(array($id, $user, $email, $birth));
	$passwordInsert->execute(array($id, $id, md5($password)));
	
	$id++;
}

if ($DEBUG == 1) {
	echo "Users:";
	$debug = $db->query("SELECT * FROM users");
	foreach($debug as $row) {
		echo '<p>' . $row['id'] . " " . $row['name'] . " " . $row['email'] . " " . $row['birth'] . '</p>';
	}
	
	echo "Passwords:";
	$passwords = $db->query("SELECT * FROM passwords");
	foreach($passwords as $row) {
		echo '<p>' . $row['id'] . " " . $row['userID'] . " " . $row['hashP'] . '</p>';
	}
}

# Populate Links-Users
$numUsers = $db->query("SELECT * from users");
$resultLinks = $db->query("SELECT * from links");
$rows = $resultLinks->fetchAll();
$numLinks = count($rows);
echo "numlinks = $numLinks";

$resultLinksTags = $db->query("SELECT COUNT(*) as count from linksTags");
$rows = $resultLinksTags->fetchAll();
$numLinksTags = count($rows);
echo "numlinksTags = $numLinksTags";

foreach($numUsers as $userRow) {
	$maxLinks = rand(0, $numLinks);
	$linkArray = randomArray($maxLinks);
	
	foreach ($linkArray as $linkID => $value) {
	
	#echo "<p> num: $numLinksTags " . $userRow['id'] . " " . $linkID . "</p>";
	$userLinksInsert->execute(array($numLinksTags, $userRow['id'], $linkID));
	$numLinksTags++;
	}
}

if ($DEBUG == 1) {
	echo "userLinks:";
	$debug = $db->query("SELECT * FROM userLinks");
	foreach($debug as $row) {
		echo '<p>' . $row['id'] . " " . $row['userID'] . " " . $row['linkID'] . '</p>';
	}
	
	echo "linksTags:";
	$debug = $db->query("SELECT * FROM linksTags");
	foreach($debug as $row) {
		echo '<p>' . $row['id'] . " " . $row['linkID'] . " " . $row['tagsID'] . '</p>';
	}
}


#DEBUG
?>